package first.endtoend

class User
{

    transient springSecurityService
    String lastName
    String firstName
    String username
    String password
    Address address
    String phone
    String email
    String gender
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    static constraints = {
        lastName blank: false
        firstName blank: false
        gender blank: false, inList: ['Male', 'Female']
        phone nullable: true, phone: true
        email nullable: true, email: true
        username blank: false, unique: true
        password blank: false
        address nullable: true
    }

    static transients = ['getFullname']

    static mapping = {
        password column: '`password`'
    }

    Set<Role> getAuthorities()
    {
        UserRole.findAllByUser(this).collect { it.role } as Set
    }

    def beforeInsert()
    {
        encodePassword()
    }

    def beforeUpdate()
    {
        if (isDirty('password'))
        {
            encodePassword()
        }
    }

    String getFullname()
    {
        firstName + " " + lastName
    }

    protected void encodePassword()
    {
        password = springSecurityService.encodePassword(password)
    }


    public String toString()
    {
        firstName + " " + lastName
    }

}
